#include "taskworker.h"
#include <QThread>
#include "message.h"

TaskWorker::TaskWorker() {}



void TaskWorker::init(const QString &ip, quint16 port) {
  m_udp = new QUdpSocket();
  m_serverAddr = QHostAddress(ip);
  m_port = port;

  // 有数据可读的信号,Qt::DirectConnection,确保在子线程中执行。
  connect(m_udp, &QUdpSocket::readyRead, this, &TaskWorker::onReadyRead,
          Qt::DirectConnection);


  //心跳定时器
  m_timer = new QTimer();
  connect(m_timer,&QTimer::timeout,this,[=](){
      Message message;
      m_udp->writeDatagram(message.toByteArray(),m_serverAddr,m_port);
  });
  m_timer->start(1000);//1s 发送一次心跳包


  // 连接到TCP服务端
  qDebug() << "connect 连接 " << QThread::currentThreadId();
}


void TaskWorker::onReadyRead() {
  qDebug() << "接收数据 " << QThread::currentThreadId();
      //是否有数据抵达
  while ( m_udp->hasPendingDatagrams())
  {
      //获取要读取数据的大小
      int size = m_udp->pendingDatagramSize();

      //定义一块缓冲区，来接收数据
      QByteArray arr;
      arr.resize(size);

      QHostAddress  addr; //发送方的IP
      quint16  port;//发送方的端口

      //接收数据的同时，获取到对方的IP与端口
      int rel = m_udp->readDatagram(arr.data(),size, &addr,&port);

      if(rel > 0)
      {
          QHostAddress  ipv4 (addr.toIPv4Address());
          Message message(arr);
          QString str = QString("接收到%1:%2的消息: %3")
                            .arg(ipv4.toString()).arg(port).arg(message.getMessage());

          emit  showMessage(str);

      }

  }
}


void TaskWorker::onSend(const QString &data) {
  qDebug() << "onSend threadId=" << QThread::currentThreadId();
  Message message(data);
  m_udp->writeDatagram(message.toByteArray(),m_serverAddr,m_port);
}

void TaskWorker::onClose() {
  qDebug() << "onClose " << QThread::currentThreadId();

  // 关闭与服务端的连接
  m_udp->disconnectFromHost();
  m_udp->deleteLater();
  m_timer->stop();
  m_timer->deleteLater();
}
